// src/plugins/mathjax.ts
import type { App } from "vue";

declare global {
  interface MathJaxConfig {
    loader:{

    },
    tex: {
      inlineMath: [string, string][];
      displayMath: [string, string][];
      processEscapes: boolean;
      packages:[string,string, string];
    };
  
    svg: {
      fontCache: string;
      fontURL: string;
      
    };
    options: {
      incremental:any;
      processHtmlClass:string;
      skipHtmlTags:[string,string, string,string,string, string]
      ignoreHtmlClass:string;
   
    };
   
    startup?: {
      pageReady: () => Promise<void>;
    };
  }

  interface Window {
    MathJax: MathJaxConfig;
  }
}

let mathJaxLoaded = false;
let mathJaxLoading = false;
const pendingElements: Element[] = [];

export const MathJaxPlugin = {
  install(app: App) {
    const loadMathJax = async () => {
      if (mathJaxLoaded || mathJaxLoading) return;

      mathJaxLoading = true;

      try {
        // 检查是否已存在 MathJax
        if (window.MathJax) {
          console.log("使用现有 MathJax 实例");
          mathJaxLoaded = true;
          return;
        }

        // 导入 MathJax
        await import("mathjax/es5/tex-svg.js"); // 替换为 SVG 渲染

        // 配置 MathJax 并使用 startup
        window.MathJax = {
          loader: {
            load: ['[tex]/tagformat','input/tex-base','[tex]/mhchem','output/chtml', '[tex]/action',],
             // 必备基础库 // 必备基础库，用来将tex转换成html  // [tex]/action库包含了\require等宏，可以用来加载其他的宏包
          },
          tex: {
            inlineMath: [
              ["$", "$"],
            ["\\(", "\\)"],
            ],
            displayMath: [
          ["$$", "$$"],
            ["\\[", "\\]"],
            ],
           
            
            packages: ['base','action','mhchem'],
            processEscapes: true  // ← 必须启用转义处理
          },
          svg: {
            fontCache: "global", // 保留缓存，但不指定字体路径
            fontURL: 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/output/svg/fonts',
          },
          options: {
            incremental: true, // 允许增量渲染不完整公式
            processHtmlClass: "math", // 为公式元素添加类名，便于选择
            skipHtmlTags: ["noscript", "style", "textarea", "pre", "code", "a"],
            ignoreHtmlClass: "tex2jax_ignore",
          },
          startup: {
            pageReady: () => {
              console.log("MathJax 初始化完成");
              mathJaxLoaded = true;

              if (pendingElements.length > 0) {
                window.MathJax.typeset(pendingElements);
                pendingElements.length = 0;
              }

              return Promise.resolve();
            },
          },
        };
      } catch (error) {
        console.error("加载 MathJax 失败:", error);
      } finally {
        mathJaxLoading = false;
      }
    };

    // 立即加载
    loadMathJax();
console.log(window.MathJax.tex)
    // 添加全局方法
    // src/plugins/mathjax.ts 仅修改 $renderMath 方法
    app.config.globalProperties.$renderMath = async (element: Element) => {
      if (!element || element.getAttribute("data-math-rendered")) return;

      if (mathJaxLoaded && window.MathJax) {
        try {
          // 等待清理和渲染完成
          await window.MathJax.typesetPromise([element]);
          element.setAttribute("data-math-rendered", "true");
        } catch (error) {
          console.error("MathJax 渲染失败:", error);
        }
      } else {
        pendingElements.push(element);
      }
    };
  },
};
